package com.geepi.listerner;

import java.io.IOException;
import java.util.ArrayList;
import java.sql.Timestamp;
import javax.servlet.ServletException;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class SessionCounter implements HttpSessionListener,ServletRequestListener {
	private static final String CONTENT_TYPE = "text/html; charset=GBK";
	private HttpServletRequest request;
	private static ArrayList list = new ArrayList();//用来存放不同ip的地址 
    private static int activeSessions = 0;//当前活动的人数

	public void init() throws ServletException {
	} 
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
	    response.setContentType(CONTENT_TYPE);
	    HttpSession session = request.getSession();
	} 
	
	@Override
	public void requestDestroyed(ServletRequestEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void requestInitialized(ServletRequestEvent sre) {
		// TODO Auto-generated method stub
        request=(HttpServletRequest)sre.getServletRequest();
	}

	public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        String sessionId = httpSessionEvent.getSession().getId();
        Timestamp createTime = new Timestamp(System.currentTimeMillis());
        String loginIp = request.getRemoteAddr();
        boolean rs = true;
        if(list.size() > 0){
            for(int i = 0;i < list.size(); i ++){
                if(loginIp.equals(list.get(i))){
                    rs = false;
                }
            }
        }
        if(rs){                      //如果队列中存在相同的IP 则SESSION不增加
            list.add(loginIp);
            System.out.println("ipList队列新增ip: "+loginIp);
            activeSessions++;
            System.out.println("新增SESSION,sessionId = " + sessionId +"; createTime = " + createTime
                             + "; loginIp = " + loginIp +"; 当前总SESSION值为 "+activeSessions);
        }
    } 


	@Override
	public void sessionDestroyed(HttpSessionEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	public static int getActiveSessions() {
	        return activeSessions;
	 } 
}
